/*
 * @Date: 2022-06-22 16:59:10
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-06-30 10:11:12
 * @FilePath: \taro-music-learn\src\pages\packageA\MusicListDetail\index.tsx
 * @Description: something
 */
import { View, Image, Text } from "@tarojs/components";
import { useDidShow, useReachBottom, useRouter } from "@tarojs/taro";
import React, { useEffect, useRef, useState } from "react";
import { reqSingListDetail, reqSongDetailAction } from "@/api/songs";
import "./index.scss";
import Taro from "@tarojs/taro";
import { playCountFormat } from "@/utils";
import { AtActivityIndicator, AtAvatar, AtButton, AtIcon } from "taro-ui";
import MusicInfoItem from "@/components/MusicInfoItem";
import { fetchSongDetailInfo, TPlaySongInfo } from "@/store/playSong";
import AudioCmp from "@/components/AudioCmp";
import GoTop from "@/components/GoTop";
import LoadingCmp from "@/components/LoadingCmp";
import { useSelector } from "@/store/hooks";
import { useDispatch } from "react-redux";
export interface IMusicListInfo {
  coverImgUrl: string;
  name: string;
  description: string;
  creator: {
    avatarUrl: string;
    nickname: string;
  };
  commentCount: number;
  subscribedCount: number;
  shareCount: number;
  playCount: number;
  tracks: any[];
  trackIds: any[];
}
const index: React.FC = () => {
  const router = useRouter();
  const musicListInfoRef = useRef<IMusicListInfo>();
  const [musicListInfo, setMusicListInfo] = useState<IMusicListInfo>({
    coverImgUrl: "",
    name: "",
    description: "",
    creator: {
      avatarUrl: "",
      nickname: ""
    },
    commentCount: 0,
    shareCount: 0,
    subscribedCount: 0,
    playCount: 0,
    tracks: [],
    trackIds: []
  });
  const [musicInfoList, setMusicInfoList] = useState<TPlaySongInfo[]>([]);
  const [isCollection, setIsCollection] = useState(false);
  const [isMore, setIsMore] = useState(false);
  const [isOpened, setIsOpened] = useState(false);
  useReachBottom(() => {
    console.log("onReachBottom");
    if (!isMore) {
      Taro.atMessage({
        type: "error",
        message: "没有更多数据了~~"
      });
      return;
    }
    console.log(musicListInfo.trackIds.length, musicListInfo.tracks.length);
    let arr = musicListInfo.trackIds.slice(
      musicListInfo.tracks.length,
      musicListInfo.tracks.length + 20
    );
    console.log(arr, "musicListInfo.trackIds");
    let ids = arr.reduce((prev, cur) => {
      return cur.id + "," + prev;
    }, "");
    ids = ids.substring(0, ids.length - 1);
    fetchSongDetailInfoByIds(ids);
  });
  const { UserState } = useSelector(state => ({
    UserState: state.User
  }));
  const dispatch = useDispatch();
  useDidShow(() => {
    fetchSingListDetail(router.params.id!);
    const flag = UserState.collectionMusicList.some(item => {
      return item.id === router.params.id!;
    });
    setIsCollection(flag);
  });
  const fetchSingListDetail = async (id: number | string) => {
    let res = await reqSingListDetail(id);
    if (res.data.code === 200) {
      console.log("信息是", res.data.playlist);
      setMusicListInfo(res.data.playlist);
      musicListInfoRef.current = res.data.playlist;
      Taro.setNavigationBarTitle({
        title: res.data.playlist.name
      });
      if (res.data.playlist.tracks.length < res.data.playlist.trackIds.length) {
        setIsMore(true);
      }
      let ids = res.data.playlist.tracks.reduce((prev, cur) => {
        return cur.id + "," + prev;
      }, "");
      ids = ids.substring(0, ids.length - 1);
      console.log(musicListInfo.trackIds.length);

      fetchSongDetailInfoByIds(ids);
    }
  };
  const fetchSongDetailInfoByIds = async (ids: string) => {
    setIsOpened(true);
    const res = await reqSongDetailAction(ids);
    if (res.data.code === 200) {
      const arr = [...musicInfoList];
      arr.push(...res.data.songs);
      setMusicInfoList(arr);
      setIsOpened(false);
      if (arr.length < musicListInfoRef.current?.trackIds.length!) {
        setIsMore(true);
      } else {
        setIsMore(false);
      }
    }
  };
  const playMusic = (id: string) => {
    dispatch<any>(fetchSongDetailInfo(id));
  };
  return (
    <View id="music-list-detail-unique">
      <GoTop />
      <LoadingCmp />
      <View className="music-list-detail-header">
        <Image
          className="music-list-detail-header-bg"
          lazyLoad
          src={musicListInfo.coverImgUrl + "?imageView&blur=40x20"}
        ></Image>
        <View className="music-list-cover-img">
          <Image
            className="img"
            lazyLoad
            src={musicListInfo.coverImgUrl}
          ></Image>
          <View className="playCount">
            <AtIcon value="play" size="5"></AtIcon>
            {playCountFormat(musicListInfo.playCount)}
          </View>
        </View>
        <View className="music-list-info">
          <Text className="music-list-name">{musicListInfo.name}</Text>
          <View className="music-list-creator-info">
            {/* {musicListInfo} */}
            <AtAvatar
              circle
              size="small"
              image={musicListInfo.creator && musicListInfo.creator.avatarUrl}
            ></AtAvatar>
            <View style={{ margin: "0 0.625rem" }}>
              {musicListInfo.creator && musicListInfo.creator.nickname}
            </View>
            <AtButton circle size="small">
              <Text style={{ color: "#ccc" }}>关注</Text>
            </AtButton>
          </View>
          <View className="music-list-name">{musicListInfo.description}</View>
        </View>
      </View>
      <View className="music-list-detail-container">
        <View className="music-info-box">
          <View className="music-info-item">
            <AtIcon
              value={isCollection ? "check-circle" : "add-circle"}
              size={20}
            ></AtIcon>
            {playCountFormat(musicListInfo.subscribedCount)}
          </View>
          <View className="music-info-item">
            <AtIcon value="align-center" size={20}></AtIcon>
            {playCountFormat(musicListInfo.commentCount)}
          </View>
          <View className="music-info-item">
            <AtIcon value="share" size={20}></AtIcon>
            {playCountFormat(musicListInfo.shareCount)}
          </View>
        </View>
        {musicInfoList.map((item, index) => {
          return (
            <View
            // onClick={() => {
            //   playMusic(item.id + "");
            // }}
            >
              <MusicInfoItem
                index={index + 1}
                songInfo={item}
                key={item.id}
              ></MusicInfoItem>
            </View>
          );
        })}
        <AtActivityIndicator
          content="玩命加载中..."
          isOpened={isOpened}
          color="#ff0000"
        ></AtActivityIndicator>
      </View>
      <AudioCmp></AudioCmp>
    </View>
  );
};
export default index;
